import { createRouteMap } from './create-route-map'
import { normalizeLocation } from './utils/location'
import { createRoute } from './utils/route'
const { compile } = require('path-to-regexp')

export default class CreateMatchers {
  constructor (routes, router) {
    const { pathList, pathMap, nameMap } = createRouteMap(routes)
    this.routes = routes
    this.router = router
    this.pathList = pathList
    this.pathMap = pathMap
    this.nameMap = nameMap
  }

  match (raw) {
    const location = normalizeLocation(raw)
    const { name, path } = location
    if (name) {
      const record = this.nameMap[name]
      if (!record) {
        return createRoute(null, location)
      }
      location.path = compile(record.path)(location.params)

      return createRoute(record, location)
    } else if (path) {
      location.param = {}
      for (let i = 0; i < this.pathList.length; i++) {
        const currentPath = this.pathList[i]
        if (this.pathMap[currentPath].regex.test(path)) {
          location.path = this.pathMap[currentPath].path
          const record = this.pathMap[currentPath]
          return createRoute(record, location)
        }
      }
    }
  }
}
